<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

use library\service\NodeService;
use think\Db;

/**
 * 打印输出数据到文件
 * @param mixed $data 输出的数据
 * @param bool $force 强制替换
 * @param string|null $file
 */
function p($data, $force = false, $file = null)
{
    is_null($file) && $file = env('runtime_path') . date('Ymd') . '.txt';
    $str = ((is_string($data) ? $data : (is_array($data) || is_object($data))) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
    $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
}

/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}


function uuid()
{
    mt_srand((double)microtime() * 10000);
    $charid = strtoupper(md5(uniqid(rand(), true)));
    $hyphen = chr(45);
    $uuid = substr($charid, 0, 8) . $hyphen
        . substr($charid, 8, 4) . $hyphen
        . substr($charid, 12, 4) . $hyphen
        . substr($charid, 16, 4) . $hyphen
        . substr($charid, 20, 12);
    return $uuid;
}

function rand_code($length)
{
    $str = "";
    while ($length--) {
        $str .= rand(0, 9);
    }
    return $str;
}

function rand_str($length)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}

//毫秒时间
/**
 * @param string $format
 * @param null $utimestamp
 * @return false|string
 */
function uDate($format = 'u', $utimestamp = null)
{
    if (is_null($utimestamp))
        $utimestamp = microtime(true);

    $timestamp = floor($utimestamp);
    $milliseconds = intval(round(($utimestamp - $timestamp) * 1000000) / 1000);

    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

function strToDate($value)
{
    return date('Y-m-d H:i:s', $value);
}

function moneyFormat($value)
{
    return number_format($value / 100, 2);
}

function filterZero($value)
{
    return $value > 0;
}

function filterUserOrderZero($value)
{
    return $value['order_count'] > 0;
}

/**
 * key1=value1&key2=value2转array
 * @param $str
 * key1=value1&key2=value2的字符串
 * @param $$needUrlDecode 是否需要解url编码，默认不需要
 */
function parseQString($str, $needUrlDecode = false)
{
    $result = array();
    $len = strlen($str);
    $temp = "";
    $curChar = "";
    $key = "";
    $isKey = true;
    $isOpen = false;
    $openName = "\0";

    for ($i = 0; $i < $len; $i++) {
        $curChar = $str[$i];
        if ($isOpen) {
            if ($curChar == $openName) {
                $isOpen = false;
            }
            $temp .= $curChar;
        } elseif ($curChar == "{") {
            $isOpen = true;
            $openName = "}";
            $temp .= $curChar;
        } elseif ($curChar == "[") {
            $isOpen = true;
            $openName = "]";
            $temp .= $curChar;
        } elseif ($isKey && $curChar == "=") {
            $key = $temp;
            $temp = "";
            $isKey = false;
        } elseif ($curChar == "&" && !$isOpen) {
            putKeyValueToDictionary($temp, $isKey, $key, $result, $needUrlDecode);
            $temp = "";
            $isKey = true;
        } else {
            $temp .= $curChar;
        }
    }

    putKeyValueToDictionary($temp, $isKey, $key, $result, $needUrlDecode);
    return $result;
}


function putKeyValueToDictionary($temp, $isKey, $key, &$result, $needUrlDecode)
{
    if ($isKey) {
        $key = $temp;
        if (strlen($key) == 0) {
            return false;
        }
        $result [$key] = "";
    } else {
        if (strlen($key) == 0) {
            return false;
        }
        if ($needUrlDecode)
            $result [$key] = urldecode($temp);
        else
            $result [$key] = $temp;
    }
}

/**
 * 取得备份文件名
 *
 * Enter description here ...
 * @param $path
 */
function getBackupFileName($path)
{
    $i = strrpos($path, ".");
    $leftFileName = substr($path, 0, $i);
    $rightFileName = substr($path, $i + 1);
    $newFileName = $leftFileName . '_backup.' . $rightFileName;
    return $newFileName;
}

/**
 * 字符串转换为 数组
 *
 * @param  $str
 * @return
 * multitype:unknown
 */
function convertStringToArray($str)
{
    return parseQString($str);
}


function getProjName()
{
    $dir = str_replace("\\", "/", dirname(__FILE__));
    $rootDir = str_replace("\\", "/", $_SERVER ['DOCUMENT_ROOT']);
    if ($rootDir[strlen($rootDir) - 1] != "/") $rootDir = $rootDir . "/";
    $index = strlen($rootDir);
    $dir = substr($dir, $index);
    $index = strpos($dir, "/");
    $projName = substr($dir, 0, $index);
    return $projName;
}

//获取当前时间的毫秒数
function getMilliseconds()
{
    // 获取当前的UNIX时间戳和微秒数
    $microtime = microtime();
    // 分割微秒数和秒数
    list($seconds, $microseconds) = explode(" ", $microtime);
    // 转换为毫秒
    $milliseconds = (int)round($seconds * 1000);
    $milliseconds += (int)round($microseconds * 1000);
    return $milliseconds;
}

/**
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\Exception
 */
function updateQueueLog($queue_title, $log)
{
    $res = Db::name('SystemQueue')->where('title', $queue_title)->find();
    if ($res) {
        Db::name('SystemQueue')->where('id', $res['id'])
            ->update(['desc' => $log]);
    }
}

